import 'package:flutter_admin/models/user_info.dart';
import 'package:flutter_admin/pages/common/cry/cry.dart';
import 'package:flutter_admin/pages/common/cry/cry_button_bar.dart';
import 'package:flutter_admin/pages/common/cry/cry_buttons.dart';
import 'package:flutter_admin/pages/common/cry/cry_dialog.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select.dart';
import 'package:flutter_admin/pages/common/cry/model/order_item_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/pages/common/cry/cry_data_table.dart';
import 'package:flutter_admin/api/odoo/product_userhourcost_odoo_api.dart';
import 'package:flutter_admin/constants/enum.dart';
import 'package:flutter_admin/generated/l10n.dart';
import 'package:flutter_admin/pages/common/cry/model/page_model.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/models/odoo/product_userhourcost.dart';
import 'package:flutter_admin/pages/odoo/product_userhourcost/product_userhourcost_edit.dart';
import 'package:flutter_admin/pages/odoo/product_userhourcost/product_userhourcost_dialog.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/pages/common/cry/vo/select_option_vo.dart';
import 'package:flutter_admin/api/odoo/dynamic_data_api.dart';
import 'package:flutter_admin/pages/odoo/product_userhourcost/product_usermeritpay_detail_list.dart';
import 'package:flutter_admin/utils/adaptive_util.dart';
import 'package:flutter_admin/utils/store_util.dart';
import 'package:flutter_admin/utils/utils.dart';

class ProductUserhourcostList extends StatefulWidget {
  ProductUserhourcostList({Key? key}) : super(key: key);

  @override
  _ProductUserhourcostListState createState() =>
      _ProductUserhourcostListState();
}

class _ProductUserhourcostListState extends State<ProductUserhourcostList> {
  final GlobalKey<CryDataTableState> tableKey = GlobalKey<CryDataTableState>();
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> scaffoldStateKey = GlobalKey<ScaffoldState>();
  PageModel page =
      PageModel(orders: [OrderItemModel(column: 'create_date', asc: false)]);
  ProductUserhourcost productUserhourcost = ProductUserhourcost();
  List<ProductUserhourcost> selectedList = [];
  //车间名称
  List<SelectOptionVO> workshopIdList = [];
  //设备工位
  List<SelectOptionVO> stationIdList = [];

  UserInfo userInfo = StoreUtil.getCurrentUserInfo();

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance!.addPostFrameCallback((c) {
      _query();
      _loadSelectVO();
    });
  }

  _loadSelectVO() async {
    if (userInfo.major != null) {
      workshopIdList = await DynamicDataApi.getModelSelect(
          model: "hr.department",
          name: "complete_name",
          key: "parent_id",
          operator: "!=",
          val: null);
    } else {
      stationIdList = await DynamicDataApi.getModelSelect(
          model: "base.productionstation",
          name: "stationname",
          key: 'workshop_id',
          val: int.parse(userInfo.deptId!));
      productUserhourcost.workshopId = userInfo.deptId;
    }
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    UserInfo userInfo = StoreUtil.getCurrentUserInfo();
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          userInfo.major != null
              ? CrySelect(
                  label: '车间名称',
                  width: 280,
                  dataList: workshopIdList,
                  value: productUserhourcost.workshopId,
                  onSaved: (v) => {productUserhourcost.workshopId = v},
                  onChange: (v) async {
                    if (productUserhourcost.workshopId != v) {
                      productUserhourcost.workshopId = v;
                      productUserhourcost.id = null;
                      try {
                        stationIdList = await DynamicDataApi.getModelSelect(
                            active: false,
                            model: "base.productionstation",
                            name: "stationname",
                            key: 'workshop_id',
                            val: int.parse(v));
                      } catch (e) {
                        stationIdList = [];
                      }
                      setState(() {});
                    }
                  },
                )
              : CryInput(
                  width: 200,
                  label: '生产车间',
                  enable: false,
                  value: userInfo.deptName,
                ),
          CrySelect(
            label: '设备工位',
            width: 280,
            dataList: stationIdList,
            value: productUserhourcost.stationId,
            onSaved: (v) => {productUserhourcost.stationId = v},
          ),
        ],
      ),
    );

    CryDataTable table = CryDataTable(
      key: tableKey,
      title: "数据列表",
      actions: !isDisplayDesktop(context)
          ? [
              _operationList(),
            ]
          : [],
      onPageChanged: (firstRowIndex) {
        page.current = (firstRowIndex ~/ page.size + 1);
        _loadData();
      },
      onRowsPerPageChanged: (int size) {
        page.size = size;
        page.current = 1;
        _loadData();
      },
      onSelectChanged: (Map selected) {
        this.setState(() {});
      },
      columns: [
        DataColumn(label: Text('车间名称')),
        DataColumn(label: Text('工厂名称')),
        DataColumn(label: Text('设备工位')),
        DataColumn(label: Text('生产日期')),
        DataColumn(label: Text('报工产量')),
        DataColumn(label: Text('工时费用')),
        DataColumn(label: Text('模具切换次数')),
        DataColumn(label: Text('模具切换费用')),
        DataColumn(label: Text('备注')),
        DataColumn(label: Text('创建人')),
        DataColumn(label: Text('创建日期')),
      ],
      getCells: (m) {
        ProductUserhourcost productUserhourcost =
            ProductUserhourcost.fromMap(m);
        return [
          DataCell(Text(productUserhourcost.workshopName ?? '--')),
          DataCell(Text(productUserhourcost.factoryName ?? '--')),
          DataCell(Text(productUserhourcost.stationName ?? '--')),
          DataCell(Text(productUserhourcost.productdate ?? '--')),

          DataCell(Text(productUserhourcost.reportyield ?? '--')),
          DataCell(Text(productUserhourcost.hourcost ?? '--')),
          DataCell(Text(productUserhourcost.mouldcount ?? '--')),
          DataCell(Text(productUserhourcost.mouldcost ?? '--')),
          DataCell(Text(productUserhourcost.remark ?? '--')),
          DataCell(Text(productUserhourcost.createName ?? '--')),
          DataCell(Text(productUserhourcost.createDate ?? '--')),
          // DataCell(Text(productUserhourcost.writeUid ?? '--')),
          // DataCell(Text(Utils.timeUTC(productUserhourcost.writeDate) ?? '--')),
        ];
      },
    );
    _getSelectList();
    CryButtonBar buttonBar = CryButtonBar(
      children: <Widget>[
        CryButtons.query(context, () => _query()),
        CryButtons.reset(context, () => _reset()),
        CryButtons.add(context, () => _edit(null)),
        CryButtons.edit(context,
            selectedList.length != 1 ? null : () => _edit(selectedList[0])),
        CryButtons.delete(context,
            selectedList.length < 1 ? null : () => _delete(selectedList)),
        CryButton(
            label: '查看绩效工资',
            iconData: Icons.view_headline,
            onPressed: selectedList.length == 1
                ? () => _coefficient(selectedList[0])
                : null),
        CryButton(
          label: "导出",
          onPressed: selectedList.length != 0
              ? () => _generateExcel(selectedList)
              : null,
          iconData: Icons.import_export_outlined,
        )
      ],
    );
    var result = Scaffold(
      key: scaffoldStateKey,
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          SizedBox(height: 10),
          Wrap(
            children: [
              isDisplayDesktop(context) ? form : Container(),
              Padding(
                padding: EdgeInsets.only(top: 24),
                child: isDisplayDesktop(context) ? buttonBar : Container(),
              )
            ],
          ),
          Expanded(child: SingleChildScrollView(child: table)),
        ],
      ),
    );
    return result;
  }

  _edit(ProductUserhourcost? productUserhourcost) async {
    showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: ProductUserhourcostEdit(
          productUserhourcost: productUserhourcost,
        ),
      ),
    ).then((v) {
      if (v != null) {
        if(productUserhourcost == null){
          // 新增时回到第一页
          tableKey.currentState?.pageTo(0);
        }
        _loadData();
      }
    });
  }

  _coefficient(ProductUserhourcost? productUserhourcost) {
    Utils.fullscreenDialog(ProductUsermeritpayDetailList(
      productUserhourcost: productUserhourcost,
    ));
  }

  _generateExcel(List<ProductUserhourcost> selectedList) {
    List<Map> map = [
      {
        'name': 'factoryName',
        'label': '工厂名称',
        'columnWidth': 10,
      },
      {
        'name': 'workshopName',
        'label': '车间名称',
        'columnWidth': 10,
      },
      {
        'name': 'stationName',
        'label': '工位名称',
        'columnWidth': 10,
      },
      {
        'name': 'productdate',
        'label': '生产日期',
        'columnWidth': 10,
      },
      {
        'name': 'reportyield',
        'label': '报工产量',
        'columnWidth': 10,
      },
      {
        'name': 'hourcost',
        'label': '工时费用',
        'columnWidth': 10,
      },
      {
        'name': 'mouldcount',
        'label': '磨具切换次数',
        'columnWidth': 10,
      },
      {
        'name': 'mouldcost',
        'label': '磨具切换费用',
        'columnWidth': 10,
      },
      {
        'name': 'remark',
        'label': '备注',
        'columnWidth': 10,
      },
      {
        'name': 'createName',
        'label': '创建人',
        'columnWidth': 10,
      },
      {
        'name': 'createDate',
        'label': '创建日期',
        'columnWidth': 10,
      }
    ];
    Utils.generateExcel(
        fileName: "车间人员绩效工资统计", configure: map, data: selectedList);
  }

  _reset() {
    productUserhourcost = ProductUserhourcost();
    formKey.currentState!.reset();
    if (userInfo.major != null) {
      //设备工位
      stationIdList = [];
    }
    _loadData();
  }

  _query() {
    formKey.currentState?.save();
    tableKey.currentState?.pageTo(0);
    _loadData();
  }

  _loadData() async {
    ResponseBodyApi responseBodyApi = await ProductUserhourcostOdooApi.page(
        data: {"page": page, "domainList": productUserhourcost.toDomainList()});
    if (responseBodyApi.success!) {
      page = responseBodyApi.data != null ? responseBodyApi.data : PageModel();
      tableKey.currentState!.loadData(page);
      _getSelectList();
    }
  }

  _delete(List<ProductUserhourcost> selectedList) async {
    cryConfirm(context, S.of(context).confirmDelete, (context) async {
      List ids = selectedList.map((v) {
        return int.parse(v.id!);
      }).toList();
      var result = await ProductUserhourcostOdooApi.removeByIds(ids);
      if (result.success!) {
        _query();
        CryUtils.message(S.of(Cry.context).success);
      }
    });
  }

  _search() {
    return showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: ProductUserhourcostDialog(),
      ),
    ).then((v) {
      if (v != null) {
        productUserhourcost = v;
        _query();
      }
    });
  }

  _getSelectList() {
    selectedList = tableKey.currentState
            ?.getSelectedList(page)
            .map<ProductUserhourcost>((e) => ProductUserhourcost.fromMap(e))
            .toList() ??
        [];
    setState(() {});
  }

  _operationList() {
    return PopupMenuButton(
      onSelected: (dynamic v) {
        if (v == OperationType.query) {
          _search();
        } else if (v == OperationType.add) {
          _edit(null);
        } else if (v == OperationType.edit) {
          _edit(selectedList[0]);
        } else if (v == OperationType.delete) {
          _delete(selectedList);
        } else if (v == OperationType.dmsFile) {
          // 借尸还魂
          _coefficient(selectedList[0]);
        }
      },
      itemBuilder: (context) => <PopupMenuEntry<OperationType>>[
        PopupMenuItem<OperationType>(
          value: OperationType.query,
          child: ListTile(
            leading: const Icon(Icons.search),
            title: Text('查询'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.add,
          child: ListTile(
            leading: const Icon(Icons.add),
            title: Text('添加'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.edit,
          enabled: selectedList.length == 1,
          child: ListTile(
            leading: const Icon(Icons.edit),
            enabled: selectedList.length == 1,
            title: Text('修改'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.delete,
          enabled: selectedList.length != 0,
          child: ListTile(
            leading: const Icon(Icons.delete), //Icons.delete
            enabled: selectedList.length != 0,
            title: Text('删除'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.dmsFile,
          enabled: selectedList.length == 1,
          child: ListTile(
            leading: const Icon(Icons.view_headline), //Icons.delete
            enabled: selectedList.length == 1,
            title: Text('删除'),
          ),
        ),
      ],
    );
  }
}
